package com.yanqu.road.server.cmd.activity.fivehero;

import com.yanqu.road.entity.activity.fivehero.FiveHeroConfig;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.FiveHeroProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.fivehero.FiveHeroMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.property.Property;


@Cmd(code = GameProtocol.S_FIVEHERO_REVIVE_CHECK_ITEM_FROM_CROSS, desc = "")
public class CrossFiveHeroCheckItemCmd extends AbstractCommand {

    private FiveHeroProto.CrossFiveHeroCheckItemMsg reqMsg;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        reqMsg = FiveHeroProto.CrossFiveHeroCheckItemMsg.parseFrom(packet.getBytes());
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        FiveHeroConfig config = FiveHeroMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            ret = GameErrorCode.E_ACTIVITY_NO_FOUND;
            return;
        }

        for(FiveHeroProto.CrossFiveHeroAddItemMsg itemMsg : reqMsg.getGoodList()){
            long userId = itemMsg.getUserId();
            GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if(gamePlayer != null){
                UserBagItem ub = gamePlayer.getModule(BagModule.class).getUserBagItem(itemMsg.getItem());
                if(ub != null && ub.getNum() != itemMsg.getNum()){
                    long offsetNum = ub.getNum() - itemMsg.getNum();
                    if (offsetNum > 0) {
                        Property removeValue = new Property(itemMsg.getItem(), offsetNum);
                        gamePlayer.getModule(CurrencyModule.class).removeCurrency(removeValue,
                                eLogMoneyType.FiveHero, eLogMoneyType.FiveHeroReviveAddItemRecall);
                    } else {
                        ub.setNum(itemMsg.getNum());
                        log.error("CrossFiveHeroCheckItemCmd fix itemNum , itemId: {}, userId: {}, num: {}",
                                itemMsg.getItem(), userId, itemMsg.getNum());
                    }
                }
            }
        }
    }

    @Override
    public void sendData(GamePlayer player) {
        if (ret == 0) {
            return;
        }
    }
}
